# -*- coding: UTF-8 -*-
'''
@学习网站      ：https://www.python-office.com
@读者群     ：http://www.python4office.cn/wechat-group/
@作者  ：B站/抖音/微博/小红书/公众号，都叫：程序员晚枫，微信：python-office
@代码日期    ：2024/11/8 23:06
@本段代码的视频说明     ：
'''
import json
import os
import sys
import traceback
from pathlib import Path

# 设置 Qt 平台插件路径
plugin_path = Path(sys.prefix) / 'Lib' / 'site-packages' / 'PyQt5' / 'Qt5' / 'plugins'
os.environ['QT_QPA_PLATFORM_PLUGIN_PATH'] = os.path.join(plugin_path, 'platforms')

from constants import UIStyle, UILabel, ConfigKey, MsgText, SystemCmd, LogName, ProgressBarName, ResourcePath, \
    ThreadMsg, FileName

from PyQt5 import QtCore
from PyQt5.QtCore import Qt, pyqtSignal, QThread
from PyQt5.QtGui import QFont
from PyQt5.QtGui import QPixmap, QIcon
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QPushButton, QStackedWidget, QLabel, \
    QSpacerItem, QSizePolicy, QMessageBox, QGridLayout, QLineEdit, QFileDialog, QTextEdit, QProgressBar

import pobd

from loguru import logger


class MainWindow(QWidget):
    process_status_signal = pyqtSignal(int, str)

    def __init__(self, config):
        super().__init__()
        self.config = config

        # 样式
        self.color_blue = UIStyle.COLOR_BLUE.value
        self.color_white = UIStyle.COLOR_WHITE.value
        self.cornflower_blue = UIStyle.CORNFLOWER_BLUE.value
        self.white_background_blue_text = UIStyle.WHITE_BG_BLUE_TEXT.value
        self.white_background = UIStyle.WHITE_BG.value
        self.ya_hei = UIStyle.FONT_YAHEI.value

        # UI 标签
        self.title_text = UILabel.TITLE_TEXT.value
        self.discern_social = UILabel.DISCERN_SOCIAL.value
        self.discern_divorce = UILabel.DISCERN_DIVORCE.value
        self.config_setting = UILabel.CONFIG_SETTING.value
        self.social_dir = UILabel.SOCIAL_DIR.value
        self.divorce_dir = UILabel.DIVORCE_DIR.value
        self.result_dir = UILabel.RESULT_DIR.value
        self.run_log = UILabel.RUN_LOG.value
        self.social_schedule = UILabel.SOCIAL_SCHEDULE.value
        self.submit = UILabel.SUBMIT.value
        self.close_text = UILabel.CLOSE.value
        self.result_text = UILabel.RESULT_TEXT.value
        self.select_social_dir = UILabel.SELECT_SOCIAL_DIR.value
        self.select_divorce_dir = UILabel.SELECT_DIVORCE_DIR.value
        self.select_result_dir = UILabel.SELECT_RESULT_DIR.value
        self.baidu_api_key = UILabel.BAIDU_API_KEY.value
        self.baidu_secret_key = UILabel.BAIDU_SECRET_KEY.value
        self.choose = UILabel.CHOOSE.value
        self.save = UILabel.SAVE.value

        # 配置字段
        self.input_path = ConfigKey.INPUT_PATH.value
        self.result_path = ConfigKey.RESULT_PATH.value
        self.social_path = ConfigKey.SOCIAL_PATH.value
        self.divorce_path = ConfigKey.DIVORCE_PATH.value
        self.api_key_text = ConfigKey.API_KEY.value
        self.secret_key_text = ConfigKey.SECRET_KEY.value
        self.value = ConfigKey.VALUE.value

        # 资源路径
        self.title_image = ResourcePath.TITLE_IMAGE.value
        self.logo_ico = ResourcePath.ICON.value
        self.config_file_path = ResourcePath.CONFIG_JSON.value

        # 日志与进度
        self.social_run_log_name = LogName.SOCIAL_LOG.value
        self.divorce_run_log_name = LogName.DIVORCE_LOG.value
        self.social_progress_bar_name = ProgressBarName.SOCIAL_BAR.value
        self.divorce_progress_bar_name = ProgressBarName.DIVORCE_BAR.value

        # 系统命令
        self.order = SystemCmd.ORDER.value
        self.kill_excel = SystemCmd.KILL_EXCEL.value
        self.kill_wps = SystemCmd.KILL_WPS.value

        # 消息内容
        self.success_title = MsgText.SUCCESS_TITLE.value
        self.success_text = MsgText.SUCCESS_TEXT.value
        self.fail_title = MsgText.FAIL_TITLE.value
        self.result_unselected = MsgText.RESULT_UNSELECTED.value
        self.social_dir_unset = MsgText.SOCIAL_UNSET.value
        self.divorce_dir_unset = MsgText.DIVORCE_UNSET.value
        self.config_unset = MsgText.CONFIG_UNSET.value
        self.wrong_title = MsgText.WRONG_TITLE.value
        self.all_done = MsgText.ALL_DONE.value
        self.work_done = MsgText.WORK_DONE.value
        self.error = MsgText.ERROR.value

        self.window_title = '各种图片数据自动提取到Excel'

        self.initUI()

    def resource_path(self, relative_path):
        if getattr(sys, 'frozen', False):  # 是否Bundle Resource
            base_path = sys._MEIPASS
        else:
            base_path = Path.cwd()
        return str(Path(base_path) / relative_path)  # <--- 确保返回的是 str

    def updateJson(self, jsonFile, key, value):
        try:
            with open(jsonFile, 'r', encoding="utf-8") as fr:  # 文件路径自己改成完整的
                json_all = json.load(fr)
                json_all[key] = value
            with open(jsonFile, 'w+', encoding="utf-8") as fw:
                json.dump(json_all, fw, ensure_ascii=False, indent=4)
        except:
            error = traceback.format_exc()
            logger.error(error)

    def createCardPage(self,
                       dir_label_text, result_label_text,
                       input_path_value, result_path_value,
                       run_log_name, progress_bar_name,
                       submit_handler, open_result_handler, close_handler,
                       choose_handler):
        page = QWidget()
        layout = QGridLayout(page)

        # 输入目录
        dir_label = QLabel(dir_label_text, page)
        dir_line_edit = QLineEdit()
        dir_line_edit.setText(input_path_value)
        dir_button = QPushButton(self.choose, page)
        dir_button.clicked.connect(choose_handler)

        layout.addWidget(dir_label, 0, 0)
        layout.addWidget(dir_line_edit, 0, 1)
        layout.addWidget(dir_button, 0, 2)

        # 结果目录
        result_label = QLabel(result_label_text, page)
        result_line_edit = QLineEdit()
        result_line_edit.setText(result_path_value)
        result_button = QPushButton(self.choose, page)
        result_button.clicked.connect(choose_handler)

        layout.addWidget(result_label, 1, 0)
        layout.addWidget(result_line_edit, 1, 1)
        layout.addWidget(result_button, 1, 2)

        # 日志
        run_log_label = QLabel(self.run_log, page)
        run_log_label.setAlignment(Qt.AlignRight)
        layout.addWidget(run_log_label, 2, 0)

        run_log_text = QTextEdit(self)
        run_log_text.setObjectName(run_log_name)
        layout.addWidget(run_log_text, 2, 1, 1, 2)

        # 进度条
        schedule_label = QLabel(self.social_schedule, page)
        progress_bar = QProgressBar(page)
        progress_bar.setProperty(self.value, 0)
        progress_bar.setObjectName(progress_bar_name)

        layout.addWidget(schedule_label, 3, 0)
        layout.addWidget(progress_bar, 3, 1, 1, 2)

        # 按钮
        submit_button = QPushButton(self.submit, page)
        open_button = QPushButton(self.result_dir, page)
        close_button = QPushButton(self.close_text, page)

        submit_button.clicked.connect(submit_handler)
        open_button.clicked.connect(open_result_handler)
        close_button.clicked.connect(close_handler)

        layout.addWidget(submit_button, 4, 0)
        layout.addWidget(open_button, 4, 1)
        layout.addWidget(close_button, 4, 2)

        # 空白间距
        spacer = QSpacerItem(40, 20, QSizePolicy.Minimum, QSizePolicy.Expanding)
        layout.addItem(spacer, 5, 0)
        layout.addItem(spacer, 5, 1)

        # 返回控件集合（方便你外部赋值）
        return {
            "page": page,
            "dir_line_edit": dir_line_edit,
            "result_line_edit": result_line_edit,
            "run_log_text": run_log_text,
            "progress_bar": progress_bar,
            "submit_button": submit_button,
            "open_result_btn": open_button,
            "close_button": close_button,
            "dir_button": dir_button,
            "result_button": result_button
        }

    def initUI(self):
        '''
        (1)
        创建主垂直布局
        '''
        main_layout = QVBoxLayout(self)
        main_layout.setContentsMargins(0, 0, 0, 0)  # 设置布局的四个边距都为0
        self.resize(600, 400)  # 窗口初始大小

        '''
        (2)
        创建第一个QWidget，背景色为绿色，固定高度为60
        '''
        top_widget = QWidget()
        top_widget.setStyleSheet(self.color_blue)
        top_widget.setFixedHeight(60)  # 顶部区域的 QWidget 控件 设置高度为60
        # 创建一个横向布局
        horizontal_box_layout = QHBoxLayout()

        # 创建图片标签并添加到横向布局
        image_label = QLabel()
        # 假设你有一个图片路径
        # 加载图片并调整其大小为64x64
        pixmap = QPixmap(self.title_image)
        scaled_pixmap = pixmap.scaled(120, 60, Qt.KeepAspectRatio, Qt.SmoothTransformation)  # 将图片缩放为宽 120，高 60，并保持原始宽高比
        image_label.setPixmap(scaled_pixmap)  # 缩放后的图像设置到 QLabel 上，让它显示图片
        horizontal_box_layout.addWidget(image_label)  # 把这个 QLabel 添加到你事先定义好的 QHBoxLayout 水平布局中
        horizontal_box_layout.setSpacing(20)  # 设置布局中控件之间的间距为 20 像素

        # 创建文本标签并添加到横向布局
        text_label = QLabel()
        text_label.setStyleSheet(self.color_white)  # 让标签里的文字变为白色
        horizontal_box_layout.addWidget(text_label)  # 添加到你事先定义好的 QHBoxLayout 水平布局中

        # 创建一个压缩空间控件并添加到横向布局
        # 使用QSizePolicy.Expanding作为策略可以使空间尽可能地被压缩   Expanding：水平方向可扩展，让它占满剩余空间     Minimum：垂直方向保持最小高度
        spacer_item = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)  # 创建了一个 空白占位项  40, 20 是初始宽高
        horizontal_box_layout.addItem(spacer_item)  # 把这个空白项加进横向布局   会将前面的内容（如图片和文字）“推”到左侧 居左对齐

        # 将横向布局设置为top_widget的布局
        top_widget.setLayout(horizontal_box_layout)  # 给 top_widget 设置一个布局
        # 添加到主布局
        main_layout.addWidget(top_widget)

        '''
        创建第二个QWidget，用于包含left_button_widget和self.stacked_widget的QHBoxLayout
        '''
        second_widget = QWidget()
        horizontal_layout = QHBoxLayout(second_widget)  # 创建了一个水平布局管理器，并直接绑定到 second_widget 上

        # 创建左边按钮区域，固定宽度为160
        left_button_widget = QWidget()
        left_button_widget.setFixedWidth(160)
        left_button_widget.setStyleSheet(self.cornflower_blue)
        # 创建3个按钮
        social_button = QPushButton(self.discern_social, left_button_widget)
        divorce_button = QPushButton(self.discern_divorce, left_button_widget)
        config_button = QPushButton(self.config_setting, left_button_widget)
        # 设置字体样式
        font = QFont(self.ya_hei, 12, QFont.Bold)  # 字体名称、大小、加粗
        social_button.setFont(font)
        divorce_button.setFont(font)
        config_button.setFont(font)
        text_label.setFont(font)
        social_button.setStyleSheet(self.white_background_blue_text)
        divorce_button.setStyleSheet(self.white_background_blue_text)
        config_button.setStyleSheet(self.white_background_blue_text)
        empty_space_first = QSpacerItem(40, 20, QSizePolicy.Minimum,
                                        QSizePolicy.Expanding)  # 在布局中添加空白空间  Minimum 占据更少的水平空间   Expanding 占据更多的垂直空间
        # 垂直布局用于放置按钮
        button_layout = QVBoxLayout(left_button_widget)
        button_layout.addWidget(social_button)
        button_layout.addWidget(divorce_button)
        button_layout.addWidget(config_button)
        button_layout.addItem(empty_space_first)
        button_layout.setSpacing(40)  # 控件之间的间距为 40 像素
        # 将left_button_widget添加到水平布局
        horizontal_layout.addWidget(left_button_widget)

        # 创建self.stacked_widget的QStackedWidget
        self.stacked_widget = QStackedWidget()  # 堆叠  可以显示多个页面的容器，每次只显示一个页面
        self.stacked_widget.setStyleSheet(self.white_background)

        social_widgets = self.createCardPage(
            dir_label_text=self.social_dir,
            result_label_text=self.result_dir,
            input_path_value=self.config.get(self.input_path),
            result_path_value=self.config.get(self.result_path),
            run_log_name=self.social_run_log_name,
            progress_bar_name=self.social_progress_bar_name,
            submit_handler=self.btnProcess,
            open_result_handler=self.btnProcess,
            close_handler=self.close,
            choose_handler=self.btnProcess
        )

        # 赋值控件方便后续使用
        self.text_social_dir = social_widgets["dir_line_edit"]
        self.social_result_path = social_widgets["result_line_edit"]
        self.social_run_log_text = social_widgets["run_log_text"]
        self.social_progress_bar = social_widgets["progress_bar"]
        self.select_social_dir_button = social_widgets["dir_button"]
        self.select_social_result_dir_button = social_widgets["result_button"]
        self.social_submit = social_widgets["submit_button"]
        self.social_open_result_dir = social_widgets["open_result_btn"]
        self.social_close = social_widgets["close_button"]

        page_social_card = social_widgets["page"]

        divorce_widgets = self.createCardPage(
            dir_label_text=self.divorce_dir,
            result_label_text=self.result_dir,
            input_path_value=self.config.get(self.input_path),
            result_path_value=self.config.get(self.result_path),
            run_log_name=self.divorce_run_log_name,
            progress_bar_name=self.divorce_progress_bar_name,
            submit_handler=self.btnProcess,
            open_result_handler=self.btnProcess,
            close_handler=self.close,
            choose_handler=self.btnProcess
        )
        self.text_divorce_dir = divorce_widgets["dir_line_edit"]
        self.divorce_result_path = divorce_widgets["result_line_edit"]
        self.divorce_run_log_text = divorce_widgets["run_log_text"]
        self.divorce_progress_bar = divorce_widgets["progress_bar"]
        self.select_divorce_dir_button = divorce_widgets["dir_button"]
        self.select_divorce_result_dir_button = divorce_widgets["result_button"]
        self.divorce_submit = divorce_widgets["submit_button"]
        self.divorce_open_result_dir = divorce_widgets["open_result_btn"]
        self.divorce_close = divorce_widgets["close_button"]

        page_divorce_card = divorce_widgets["page"]

        '''
        3、第三个界面内容
        '''
        page_config = QWidget()
        third_layout = QGridLayout(page_config)

        baidu_api_key_label = QLabel(self.baidu_api_key, page_config)
        self.input_api_key = QLineEdit()  # 单行文本输入框（QLineEdit），用于输入或显示 API Key
        self.input_api_key.setText(self.config.get(self.api_key_text))
        third_layout.addWidget(baidu_api_key_label, 0, 0)
        third_layout.addWidget(self.input_api_key, 0, 1)

        baidu_secret_key_label = QLabel(self.baidu_secret_key, page_config)
        self.input_secret_key = QLineEdit()
        self.input_secret_key.setText(self.config.get(self.secret_key_text))
        third_layout.addWidget(baidu_secret_key_label, 1, 0)
        third_layout.addWidget(self.input_secret_key, 1, 1)

        self.save_config = QPushButton(self.save, page_config)
        self.save_config.clicked.connect(self.btnProcess)

        third_layout.addWidget(self.save_config, 2, 0)
        empty_space_fourth = QSpacerItem(40, 20, QSizePolicy.Minimum, QSizePolicy.Expanding)
        third_layout.addItem(empty_space_fourth, 3, 0)
        third_layout.addItem(empty_space_fourth, 3, 1)

        # 将界面添加到堆叠控件 ######################################
        self.stacked_widget.addWidget(page_social_card)
        self.stacked_widget.addWidget(page_divorce_card)
        self.stacked_widget.addWidget(page_config)

        # 将self.stacked_widget添加到水平布局
        horizontal_layout.addWidget(self.stacked_widget)

        # 将第二个QWidget添加到主布局
        main_layout.addWidget(second_widget)

        # 连接按钮信号到槽函数
        social_button.clicked.connect(lambda: self.stacked_widget.setCurrentIndex(0))
        divorce_button.clicked.connect(lambda: self.stacked_widget.setCurrentIndex(1))
        config_button.clicked.connect(lambda: self.stacked_widget.setCurrentIndex(2))
        main_layout.setSpacing(0)  # 控件之间的间距为 0。
        horizontal_layout.setSpacing(0)
        horizontal_layout.setContentsMargins(0, 0, 0, 0)  # 布局与其边缘之间的内边距（边界距离）为 0。
        # 设置窗口属性
        self.setWindowIcon(QIcon(self.resource_path(self.logo_ico)))
        self.setWindowTitle(self.window_title)
        self.show()

    '''
        浏览点击事件
    '''

    def btnProcess(self):
        try:
            button = self.sender()

            if button == self.select_social_dir_button:
                default_dir = Path.cwd() / self.social_dir
                self.selectDirectory(self.select_social_dir, str(default_dir),
                                     self.text_social_dir, self.input_path)

            elif button == self.select_divorce_dir_button:
                default_dir = Path.cwd() / self.divorce_dir
                self.selectDirectory(self.select_divorce_dir, str(default_dir),
                                     self.text_divorce_dir, self.input_path)

            elif button == self.select_social_result_dir_button or button == self.select_divorce_result_dir_button:
                default_dir = Path.cwd() / self.result_text
                self.selectDirectory(self.select_result_dir, str(default_dir),
                                     self.social_result_path, self.result_path)


            elif button == self.save_config:
                self.saveConfig()

            elif button == self.social_open_result_dir:
                self.openDirectory(self.social_result_path)

            elif button == self.divorce_open_result_dir:
                self.openDirectory(self.divorce_result_path)

            elif button == self.social_submit:
                self.processCard(
                    self.text_social_dir,
                    self.social_result_path,
                    self.social_submit,
                    self.social_open_result_dir,
                    self.social_close,
                    self.social_run_log_text,
                    self.social_progress_bar,
                    self.social_path
                )

            elif button == self.divorce_submit:
                self.processCard(
                    self.text_divorce_dir,
                    self.divorce_result_path,
                    self.divorce_submit,
                    self.divorce_open_result_dir,
                    self.divorce_close,
                    self.divorce_run_log_text,
                    self.divorce_progress_bar,
                    self.divorce_path
                )

        except Exception as e:
            logger.error(traceback.format_exc())
            self.create.setEnabled(True)
            self.openDir.setEnabled(True)
            page_index = self.stacked_widget.currentIndex()
            if page_index == 0:
                self.social_close.setEnabled(True)
            else:
                self.divorce_close.setEnabled(True)

    ################ 抽象出的方法 ################
    def selectDirectory(self, title, default_path, target_line_edit, config_key):
        default_path = str(Path(default_path).resolve())  # 确保为字符串路径
        dir_path = QFileDialog.getExistingDirectory(self, title, default_path)
        if dir_path:
            target_line_edit.setText(dir_path)
            config_path = Path.cwd() / self.config_file_path
            self.updateJson(str(config_path), config_key, dir_path)

    def openDirectory(self, path_line_edit):
        path = Path(path_line_edit.text())
        if path.exists():
            os.system(f"{self.order}{str(path.resolve())}")

    def checkCommonConditions(self, dir_text, result_path):
        if not dir_text:
            QMessageBox.warning(self, self.fail_title, self.social_dir_unset)
            return False
        if not result_path:
            QMessageBox.warning(self, self.fail_title, self.result_unselected)
            return False
        if not self.config.get(self.api_key_text) or not self.config.get(self.secret_key_text):
            QMessageBox.warning(self, self.fail_title, self.config_unset)
            return False
        return True

    def processCard(self, dir_text_widget, result_text_widget,
                    submit_button, open_result_btn, close_button,
                    run_log_widget, progress_bar,
                    config_path_key):

        dir_text = dir_text_widget.text()
        result_path = result_text_widget.text()
        if not self.checkCommonConditions(dir_text, result_path):
            return

        submit_button.setEnabled(False)
        open_result_btn.setEnabled(False)
        close_button.setEnabled(False)
        run_log_widget.setText("")
        progress_bar.setValue(0)

        self.config[self.input_path] = dir_text
        self.config[self.result_path] = result_path

        self.startTransfer()

    def startTransfer(self):
        os.system(self.kill_excel)
        os.system(self.kill_wps)
        self.progress_text = ""
        self.process_thread = transferThread(self.config, self)
        self.process_thread.start()
        self.process_thread.start_process_signal.connect(self.processStatus)
        self.process_thread.exec_()

    def saveConfig(self):
        api_key = self.input_api_key.text()
        secret_key = self.input_secret_key.text()

        config_path = Path.cwd() / self.config_file_path
        self.updateJson(str(config_path), self.api_key_text, api_key)
        self.updateJson(str(config_path), self.secret_key_text, secret_key)

        self.config[self.api_key_text] = api_key
        self.config[self.secret_key_text] = secret_key

        QMessageBox.warning(self, self.success_title, self.success_text)

    '''
    处理子线程信号函数
    '''

    def processStatus(self, value, string):
        self.progress_text = f"{self.progress_text}\n{string}"

        page_index = self.stacked_widget.currentIndex()

        # 动态选择控件
        current_progress_bar = self.social_progress_bar if page_index == 0 else self.divorce_progress_bar
        current_progress_text = self.social_run_log_text if page_index == 0 else self.divorce_run_log_text
        current_submit_button = self.social_submit if page_index == 0 else self.divorce_submit
        current_open_button = self.social_open_result_dir if page_index == 0 else self.divorce_open_result_dir
        current_close_button = self.social_close if page_index == 0 else self.divorce_close

        if string == "":
            current_progress_bar.setMaximum(int(value))
            self.max_value = int(value)
        else:
            current_progress_bar.setValue(int(value))
            current_progress_text.setText(self.progress_text)

            if self.error in string:
                reply = QMessageBox.warning(self, self.wrong_title, string)
                if reply:
                    current_submit_button.setEnabled(True)
                    current_open_button.setEnabled(True)
                    current_close_button.setEnabled(True)
                    return

            elif int(value) == self.max_value and self.all_done in string:
                reply = QMessageBox.warning(self, self.success_title, self.work_done)
                if reply:
                    current_submit_button.setEnabled(True)
                    current_open_button.setEnabled(True)
                    current_close_button.setEnabled(True)
                    return


'''
子线程类，实现转换
'''


class transferThread(QThread):
    '''
    创建信号 接受字符串（这里用于主线程向子线程传递信息）
    '''
    start_process_signal = pyqtSignal(int, str)

    def __init__(self, args, main_window):
        super(transferThread, self).__init__()
        self.args = args
        self.main_window = main_window  # 主窗口引用
        self.input_path = ConfigKey.INPUT_PATH.value
        self.output_path = ConfigKey.RESULT_PATH.value
        self.api_key = ConfigKey.API_KEY.value
        self.secret_key = ConfigKey.SECRET_KEY.value
        self.conversion = ThreadMsg.CONVERSION_START.value
        self.conversion_complete = ThreadMsg.CONVERSION_DONE.value
        self.all_complete = ThreadMsg.ALL_DONE.value
        self.out_file = FileName.RESULT_EXCEL.value

    '''
    子线程主处理函数
    '''

    def run(self):
        try:
            self.start_process_signal.emit(3, "")
            input_path = self.args.get(self.input_path)
            output_path = self.args.get(self.output_path)
            api_key = self.args.get(self.api_key)
            secret_key = self.args.get(self.secret_key)
            out_file = self.out_file
            self.start_process_signal.emit(1, self.conversion)

            page_index = self.main_window.stacked_widget.currentIndex()
            first_page = 0
            second_page = 1
            if page_index == first_page:
                pobd.ocr2excel.social_security_card(img_path=input_path, output_path=output_path,
                                                    output_excel_path=out_file, api_key=api_key, secret_key=secret_key)
            elif page_index == second_page:
                pobd.ocr2excel.divorce_certificate(img_path=input_path, output_path=output_path,
                                                   output_excel_path=out_file, api_key=api_key, secret_key=secret_key)

            self.start_process_signal.emit(2, self.conversion_complete)
            self.start_process_signal.emit(3, self.all_complete)

        except:
            message = traceback.format_exc()

            self.start_process_signal.emit(1, message)


if __name__ == '__main__':
    QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling)

    app = QApplication(sys.argv)
    config = {}
    # pathlib
    config_path = Path.cwd() / "配置信息" / "sysConfig.json"

    if config_path.exists():
        with config_path.open(encoding="utf-8") as f:
            config_str = f.read()
        config = json.loads(config_str)

    ex = MainWindow(config)
    sys.exit(app.exec_())
